<template>
    <div class="main-body">
        <div class="header">
        </div>
        <div class="main">
            <div class="aside">
                <el-card class="box-card">
                    <div>
                        <p class="title">批改情况</p>
                        <div class="title-tag">
                            <el-tag type="success" size="medium">已批改</el-tag>
                            <el-tag type="info" size="medium">待批改</el-tag>
                        </div>
                    </div>
                    <div class="answer-tag-items">
                        <div v-for="i in 5">
                            <div v-if="groupList[i] !==undefined && groupList[i] != null  && groupList[i].length > 0">
                                <p class="title">{{ questionTypeList[i - 1]}}</p>
                                <div class="title-tag">
                                    <el-tag ref="tags" :type="changeTagType(question)" @click="jump(i,index)"
                                            size="medium"
                                            v-for="(question,index) in groupList[i]"
                                            :key="`${i} +'-'+ ${index}`" :id="`'a'+ ${i} +'-'+ ${index}`">
                                        <div>{{(groupInfoList[i-1].startIndex + index + 1)}}</div>
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div  style="width: 100%;">

                        <el-form ref="ruleForm" label-width="100px">
                            <el-form-item label-width="0" style="text-align: center;margin-top: 12px;">
                                <el-button type="primary" size="medium" style=""
                                           @click="checkTag" v-preventReClick>提交批改
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>

                </el-card>
            </div>
            <div class="content">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>{{examInfo.paperName}}</span>
                    </div>
                    <div>
                        <div v-for="i in 5" class="question-content">
                            <div v-if="groupList[i] !==undefined && groupList[i] != null  && groupList[i].length > 0">
                                <div>
                                    <span class="questionType">{{ questionTypeList[i - 1]}}</span>
                                    <span class="question-score">{{'（共'+groupInfoList[i-1].count+'题，'+groupInfoList[i-1].scoreSum+'分）'}}
                                        </span>
                                </div>
                                <div v-for="(question,index) in groupList[i]" :id="`${i}-${index}`" class="question">
                                    <el-row>
                                        <el-col :span="0.5">
                                        </el-col>
                                        <el-col :span="0.5">
                                            <div>{{(groupInfoList[i-1].startIndex + index + 1) + "."}}</div>
                                        </el-col>
                                        <el-col :span="23">
                                            <div class="question-title">
                                                <span class="question-content"
                                                      v-html="handleContentHTML(question.questionTitle)"></span>
                                                <span class="score">{{ questionTypeList[i - 1]+' ' + question.questionScore+'分'}}</span>
                                            </div>
                                            <div v-if="question.questionType == 1">
                                                <div class="option">
                                                    <el-radio-group v-model="form[question.questionId]" size="medium">
                                                        <el-radio label="A" border>A. {{question.optionA}}</el-radio>
                                                        <el-radio label="B" border>B. {{question.optionB}}</el-radio>
                                                        <el-radio label="C" border>C. {{question.optionC}}</el-radio>
                                                        <el-radio label="D" border>D. {{question.optionD}}</el-radio>
                                                    </el-radio-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 2">
                                                <div class="option">
                                                    <el-checkbox-group v-model="form[question.questionId]"
                                                                       size="medium">
                                                        <el-checkbox label="A" border>A. {{question.optionA}}
                                                        </el-checkbox>
                                                        <el-checkbox label="B" border>B. {{question.optionB}}
                                                        </el-checkbox>
                                                        <el-checkbox label="C" border>C. {{question.optionC}}
                                                        </el-checkbox>
                                                        <el-checkbox label="D" border>D. {{question.optionD}}
                                                        </el-checkbox>
                                                    </el-checkbox-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 3">
                                                <div class="option">
                                                    <el-radio-group v-model="form[question.questionId]" size="medium">
                                                        <el-radio label="A" border>{{question.optionA}}</el-radio>
                                                        <el-radio label="B" border>{{question.optionB}}</el-radio>
                                                    </el-radio-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 4">
                                                <div class="option">
                                                    <el-input placeholder="请输入答案" v-model="form[question.questionId]"
                                                              size="medium">
                                                        <template slot="prepend">填写答案</template>
                                                    </el-input>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 5">
                                                <div class="option">
                                                    <el-input type="textarea" size="medium" rows="5" placeholder="请输入答案"
                                                              v-model="form[question.questionId]">
                                                    </el-input>
                                                </div>
                                            </div>
                                            <!-- 正确答案、打分-->
                                            <div>
                                                <el-form ref="scoreObj" :model="scoreObj" label-width="100px">
                                                    <div>
                                                        <el-form-item label="学生作答：">
                                                            {{question.answer}}
                                                        </el-form-item>
                                                        <el-form-item label="正确答案：">
                                                            <div v-html="question.correctAnswer"></div>
                                                        </el-form-item>
                                                        <el-form-item label="满分：">
                                                            {{question.questionScore}}
                                                        </el-form-item>
                                                        <el-form-item label="获得分数：">
                                                            {{question.score}}
                                                        </el-form-item>
                                                        <el-form-item label="批改状态：">
                                                            <template slot-scope="scope">
                                                                <el-tag type="primary" v-if="question.doRight != -1">已批改
                                                                </el-tag>
                                                                <el-tag type="warning" v-if="question.doRight == -1">待批改
                                                                </el-tag>
                                                            </template>
                                                        </el-form-item>
                                                    </div>
                                                    <div v-if="question.doRight == -1||question.doRight == 2">
                                                        <el-form-item label="批改分数:">
                                                            <el-input-number v-model="question.score"
                                                                             :precision="0" :step="1" :min="0"
                                                                             :max="question.questionScore"
                                                                             @change="question.doRight = 2"
                                                            ></el-input-number>
                                                        </el-form-item>
                                                    </div>
                                                </el-form>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
        <el-dialog
                title="提示"
                :visible.sync="checkTagDialogVisible"
                width="30%"
                :before-close="handleClose">
            <span>还有题目没批改完成</span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="checkTagDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitPaper">确 定</el-button>
  </span>
        </el-dialog>
        <el-backtop target=".content"></el-backtop>
    </div>
</template>
<style>
    /*@import "../assets/css/do.css";*/
    .header {
        width: 100%;
        /*不生效*/
        height: 20px;
        position: fixed;
        border-bottom: 1px solid #e4e6e9;
        /*以下自定义样式*/
        top: 0px;
        padding: 0px;
    }

    .aside {
        position: fixed;
        top: 20px;
        bottom: 0;
        left: 0;
        width: 25%;
        /*以下自定义样式*/
        padding-left: 12px;
        padding-right: 12px;
    }

    .content {
        position: fixed;
        top: 20px;
        right: 0;
        bottom: 0;
        left: 25%;
        overflow-y: auto;
        /*以下自定义样式*/
        padding-left: 12px;
        padding-right: 12px;
    }

    .content .el-card__body {
        padding-top: 0;
    }

    /*美化单选框*/
    .option {
        margin-top: 10px;
        width: 100%;
    }

    .option .el-radio {
        display: inline-block;
        width: 100%;
        margin-left: 10px;
        margin-bottom: 10px;
    }

    .option .el-radio-group label {
        /*width: 550%;*/
    }

    .el-radio__input {
        display: none;
    }


    /*美化多选框*/
    .option .el-checkbox {
        display: inline-block;
        width: 100%;
        margin-left: 10px;
        margin-bottom: 10px;
    }

    .option .el-checkbox-group label {
        /*width: 550%;*/
    }

    .el-checkbox__input {
        display: none;
    }

    .title {
        background: #eee;
        line-height: 35px;
        text-align: center;
        font-size: 14px;
    }

    .title-tag {
        margin-left: -12px;
        margin-right: -12px;
        padding-left: 10px;
    }

    .title-tag .el-tag {
        cursor: pointer;
        margin: 10px 2px;
    }

    .questionType {
        line-height: 60px;
        font-size: 16px;
        font-weight: bold;
    }

    .question-score {
        color: #949494;
        margin-left: 6px;
        font-size: 12px;
    }

    .question {
        margin-top: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #dedede;
    }

    .question-title .score {
        font-size: 12px;
        background-color: #f4f4f4;
        border-radius: 15px;
        padding: 2px 8px;
        color: #9d9d9d;
        margin-right: 6px;
        display: inline-block;
    }

    /*    form打分*/
    .el-form-item--mini.el-form-item {
        margin-bottom: 0px;
    }
    /*button按钮居中*/
    .el-form-item{

    }

</style>
<script>

    import request from "../utils/request";
    import {serverIp} from "../../public/config";
    import {setRoutes} from "../router";

    export default {
        name: 'Check',
        components: {},
        data() {
            return {
                examInfo: {},
                form: {},
                paper: {},
                scoreObj: {},
                user: {},
                groupList: [],
                questionList: [],
                groupInfoList: [],//存储分组题目的题目总数量和总分值
                checkTagDialogVisible: false,
                time: 60,
                countdown: '加载中',
                checkboxList: {},
                questionTypeList: ['单选题', '多选题', '判断题', '填空题', '问答题'],
            }
        },
        async created() {
            this.getUser();
            this.setExamInfo();
            //0.接收参数
            this.load();
            console.log("examInfo", this.examInfo)
            //1.获取题目
            await request.get('/examInfo/getAnswer', {
                params: {
                    studentId: this.examInfo.studentId,
                    paperId: this.examInfo.paperId
                }
            }).then(res => {
                if (res.code == '200') {
                    this.questionList = res.data;
                    console.log('this.questionList', this.questionList)
                }
            })
            //2.根据试卷Id和学号获取答案
            this.preprocessData();
            //3.添加分数框
            //4.提交答案
            console.log("preprocessData后groupList", this.groupList)
        },
        mounted() {

        },
        methods: {
            load() {
                //接受传递参数
                if (localStorage.getItem('examInfo')) {
                    this.examInfo = JSON.parse(localStorage.getItem('examInfo'));
                    console.log("check中examInfo", this.examInfo)
                    return true;
                } else {
                    this.$message.error("获取试卷错误");
                    return false;
                }
            },
            getUser() {
                this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
                if (!this.user) {
                    this.$message.info("获取用户失败，请重新登录")
                }
            },
            async preprocessData() {
                //根据题型分类
                //1.数组初始化
                for (let i = 1; i < 6; i++) {
                    this.groupList[i] = [];//数组初始化
                }
                //2.按题目类型，把questionList分为groupList，数据分组
                for (const question of this.questionList) {
                    this.groupList[question.questionType].push(question);
                }
                console.log("questionList", this.questionList)

                console.log("处理结果后groupList", this.groupList)

                //统计题目,存储分组题目的题目总数量和总分值
                let i = 0;//题目类别
                let startIndex = 0;//题目起始序号
                let count = 0;
                for (let k = 1; k < 6; k++) {
                    let scoreSum = 0;
                    this.groupList[k].forEach(question => {
                        scoreSum += question.questionScore;
                    })
                    if (scoreSum != 0) {
                        i++;
                    }
                    count = this.groupList[k].length;
                    this.groupInfoList.push({'i': i, 'startIndex': startIndex, 'count': count, 'scoreSum': scoreSum});
                    startIndex += count;//是上一种题型的累计
                }
                //单独对多选题突出
                this.groupList[2].forEach(question => {
                    console.log("question", question)
                    this.$set(this.form, question.questionId, [])
                })
                //输出处理结果
                console.log("groupInfo:", this.groupInfoList)
                console.log("form:", this.form)
                console.log("groupList", this.groupList)

                //处理选择题选项
                for (const question of this.questionList) {
                    this.form[question.questionId] = question.answer
                    if (question.questionType == 2) {
                        this.form[question.questionId] = JSON.parse(question.answer);
                    }
                }
                //解决不渲染问题
                this.groupList = JSON.parse(JSON.stringify(this.groupList));
                this.groupInfoList = JSON.parse(JSON.stringify(this.groupInfoList));
                this.form = JSON.parse(JSON.stringify(this.form));
            },
            changeTagType(question) {
                if(question.doRight == -1){
                    return "info";
                }else{
                    return "success";
                }
            },
            showTime() {
                this.time = this.paper.suggestTime * 60;//秒
                let time = setInterval(() => {
                    this.time--;
                    let h = parseInt(this.time / 60 / 60 % 24)
                    h = h < 10 ? '0' + h : h
                    let m = parseInt(this.time / 60 % 60)
                    m = m < 10 ? '0' + m : m
                    let s = parseInt(this.time % 60)
                    s = s < 10 ? '0' + s : s
                    this.countdown = "";
                    if (h != "00") {
                        this.countdown += h + "时"
                    }
                    if (m != "00") {
                        this.countdown += m + "分"
                    }
                    this.countdown += s + "秒"
                    //处理考试时间结束
                    if (this.time < 0) {
                        this.submitPaper();//提交试卷
                        this.countdown = "考试结束";
                        clearInterval(time);
                    }
                }, 1000)
            },
            checkTag() {
                let tags = this.$refs.tags;
                let flag = true;//默认提交试卷
                for (let i = 0; i < tags.length; i++) {
                    if (tags[i].type == "info") {
                        flag = false;//不符合提交要求
                        this.checkTagDialogVisible = true;
                        break;
                    }
                }
                if (flag) {
                    this.submitPaper();//提交答案
                }
            },
            submitPaper() {
                //提交答案
                console.log("提交groupList",this.groupList)
                //groupList改为list
                var answerList = [];
                for (let i = 4; i < 6; i++) {
                    if(this.groupList[i].length>0){
                        for (const question of this.groupList[i]){
                            answerList.push(question);
                        }
                    }
                }
                console.log("提交answerList",answerList)
                request.post('/answer/checkPaper', answerList).then(res => {
                    console.log("code:", res.code)
                    if (res.code == '200') {
                        this.$message.success("批改成功")
                        this.$router.push({
                            path: "/exam/checkResult", name: 'CheckResult', params: {
                                examInfo: res.data,
                                text:"批改结束",
                                rollback:"/checkPaper"
                            }
                        });
                    } else {
                        this.$message.error("批改失败")
                    }
                }).catch((err) => {
                    this.$message.error(err);
                })
            },
            jump(i, index) {
                //点击答题卡，跳转到对应题目
                document.getElementById(i + "-" + index).scrollIntoView();
            },
            handleContentHTML(content) {
                return content.slice(3, -4);
            },
            handleClose() {
                this.checkTagDialogVisible = false;
            },
            searchByquestionId(questionId) {
                let question = this.paper.questionList.find(item => {
                    return item.questionId == questionId
                })
                console.log("找到了", question)
                return question;
            },
            setExamInfo() {
                this.examInfo = {
                    "id": 120,
                    "paperId": 167,
                    "paperName": "数据库固定试卷",
                    "examType": null,
                    "status": 1,
                    "courseId": "1",
                    "courseName": null,
                    "systemScore": 9,
                    "paperScore": null,
                    "fullScore": 39,
                    "questionCount": 13,
                    "correctQuestionCount": 3,
                    "doTime": 19,
                    "createTime": "2022-05-13T18:01:23.000+00:00",
                    "studentId": "3120182109222",
                    "studentName": "杨熙杰"
                };

            }


        }

    }
</script>
